<?php

namespace App\Services\MakeSeckillOrder;

use App\Models\User;
use Carbon\Carbon;
use App\Models\Address;
use App\Models\Order;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Illuminate\Support\Facades\Redis;

class ConfirmSeckillOrderRequest extends FormRequest
{
	public function rules()
	{

		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}
		return [
			'address_id' => ['required', $this->address()],
			'cache_ids' => ['required','array', $this->seckillCache()]
			
		];
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			if (!$this->address) {
				return $fail('地址不存在');
			}
			return true;
		};
	}

	public function seckillCache()
	{
		return function ($attribute, $value, $fail) {
			foreach($value as $k=>$v){
				if (!Redis::exists($v)) {
					return $fail('订单不存在或已过期');
				}elseif(Redis::hGet($v,'address')){
					return $fail('订单已确认');
				}elseif(Redis::hGet($v,'closed_at')){
					return $fail('订单已关闭');
				}

				$unallowedArea = Redis::hGet($v,'unallowed_area');
				if($unallowedArea){
					$provinces = explode(",",$unallowedArea);
					if(in_array($this->address->province,$provinces)){
						return $fail('地址不在配送范围');
					}				
				}
			}
			return true;
		};
	}

	public function getAddress(): Address
	{
		return $this->address;
	}
}
